package com.zrf.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.zrf.hibernate.pojo.Buyer;
import com.zrf.tool.Tools;

@Repository("buyerDao")
public class BuyerDaoImpl extends BaseDaoImpl<Buyer>{

	private Session session = null;
	private Query query = null;
	private Transaction transaction = null;
	private Tools tools = null;
	
	
	
	
	//买家登录
	public boolean login(String name,String password){
		boolean result = false;
		String hql = "FROM Buyer b WHERE b.bname=? AND b.bpassword=?";
		
		try {
			session = this.getHibernateTemplate().getSessionFactory().openSession();
			query = session.createQuery(hql);
			query.setString(0, name);
			query.setString(1, password);
			if(query.list()!=null && query.list().size()==1){
				result = true;
			}
		
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		if(session!=null && session.isOpen()){
			session.close();
		}
		return result;

	}
	
	
	//买家注册
	public boolean reg(String name,String password){
		boolean result  = false;
		try {
			
			Integer id = 0;
			Buyer b = null;
			List<?> list = null;
			
			String hql = "FROM Buyer b WHERE b.bname=?";
			session = this.getHibernateTemplate().getSessionFactory().openSession();
			transaction = session.beginTransaction();
			
			query = session.createQuery(hql);
			query.setString(0, name);
			list = query.list();
			if(list==null || list.size()<1){                    //不重名可注册判断
				hql = "SELECT b.buyerid FROM Buyer b";
				query = session.createQuery(hql);
				list = query.list();
				if(list.size()<=0){                                 //查ID数，随机生成不重复ID
					list = null;
				}
				tools  = new Tools();
				id = tools.getListID(list);
				b = new Buyer(id);
				b.setBname(name);
				b.setBpassword(password);
				
				session.save(b);
				transaction.commit();
				result = true;
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
		if(session!=null && session.isOpen()){
			session.close();
		}
		
		
		return result;
	}
	
	
	//根据用户名查找用户
	public Buyer findByName(String bname){
		Buyer b = null;
		List<?> list = null;
		String hql = "FROM Buyer b WHERE b.bname=?";
		try {
			session = this.getHibernateTemplate().getSessionFactory().openSession();
			query = session.createQuery(hql);
			query.setString(0, bname);
			list = query.list();
			if(list!=null && list.size()>0){
				b = (Buyer) list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
		if(session!=null && session.isOpen()){
			session.close();
		}
		
		return b;
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
